<template>
  <app-section :loading="pageLoading">
    <van-nav-bar
      title="选择用户"
      @click-left="backRoute"
      @click-right="saveSelected"
      left-arrow
      left-text="返回"
      right-text="确定">
    </van-nav-bar>
    <van-cell-group>
      <van-field
        clearable
        v-model="keyword"
        right-icon="search"
        placeholder="请输入关键字查询部门"
        @click-right-icon="onRefresh"
        @input="searchByKeyword">
      </van-field>
    </van-cell-group>
    <van-pull-refresh v-model="pullLoading" @refresh="onRefresh">
      <van-checkbox-group v-model="selectedList">
        <van-cell v-for="(item,index) in depList" :key="index" clickable @click="toggleChecked(index)">
          <van-checkbox ref="checkBoxRef" slot="icon" :name="item"/>
          <span slot="title" style="margin-left: 5px;">
           <span v-for="n in item.level" :key="n" style="width:15px;display: inline-block"></span>
            <van-icon v-if="item.level===0" name="wap-home-o" />
            <van-icon v-else-if="item.level===1" name="cluster-o" />
            {{ item.departName }}
          </span>
        </van-cell>
      </van-checkbox-group>
    </van-pull-refresh>
  </app-section>
</template>

<script>
  import AppSection from '@/components/AppSection'
  import { getAction } from '@/api'
  import debounce from 'lodash/debounce';

  export default {
    name: 'SelectDeparts',
    components:{
      AppSection
    },
    data(){
      this.searchByKeyword = debounce(this.searchByKeyword, 1000);//消抖
      return {
        pageLoading:false,
        pullLoading: false,
        listLoading: false,
        listFinished:false,
        finishedText:'没有更多了',
        listError:false,
        pageNo:1,
        pageSize:10,
        url:"/sys/sysDepart/queryTreeList",
        depList:[],
        metaList:[],
        selectedList:[],
        keyword:'',
        selectIdArray:[]
      }
    },
    created(){
      this.onRefresh();
      console.log(111)
    },
    methods:{
      backRoute(){
        this.$emit("back")
      },
      getSelectValue(ids){
        let arr = [];
        this.metaList.map(item=>{
          if(ids.indexOf(item.id)>=0){
            arr.push(item.departName)
          }
        });
        return arr.join(',')
      },
      saveSelected(){
        let arr = this.backUsefulData()
        this.$emit("ok",arr)
      },
      searchByKeyword(){
        let arr = [];
        this.metaList.map(item=>{
          if(item.departName.indexOf(this.keyword)>=0){
            if(arr.indexOf(item.id)<0){
              arr.push(item.id);
              this.findAllParent(arr, item);
            }
          }
        });

        let ls = [];
        this.metaList.map(item=>{
         if(arr.indexOf(item.id)>=0){
           ls.push(item)
         }
        });
        this.depList = [...ls]
      },
      findAllParent(arr, node){
        if(node.pid && node.pid.length>0){
          this.metaList.map(item=>{
            if(item.id === node.pid && arr.indexOf(item.id)<0){
              arr.push(item.id);
              this.findAllParent(arr, item);
            }
          })
        }
      },
      onRefresh() {
        this.pullLoading = true;
        this.depList=[];
        this.metaList=[];
        getAction(this.url).then(res=>{
          this.pullLoading = false;
          if(res.success){
            let arr = []
            this.treeDataHandler(res.result, 0, arr)
            for(let item of arr){
              this.depList.push(item);
              this.metaList.push(item);
              if(this.selectIdArray.indexOf(item.id)>=0){
                this.selectedList.push(item)
              }
            }
          }
        })
      },
      treeDataHandler(treeList,level,arr){
        for(let item of treeList){
          arr.push({
            id: item.id,
            level: level,
            departName: item.departName,
            orgCode: item.orgCode,
            virtual:false,
            pid:item.parentId
          });
          if(item.children && item.children.length>0){
            this.treeDataHandler(item.children,level+1,arr)
          }
        }
      },
      clearAll(ids){
        this.selectedList=[];
        this.selectIdArray = [];
        if(ids && ids.length>0){
          this.selectIdArray = ids.split(',');
          for(let item of this.depList){
            if(this.selectIdArray.indexOf(item.id)>=0){
              this.selectedList.push(item)
            }
          }
        }
      },
      backUsefulData(){
        let arr = [];
        for(let item of this.selectedList){
          let obj = {
            departName:item.departName,
            id:item.id
          };
          arr.push(obj)
        }
        return arr;
      },
      toggleChecked(index){
        this.$refs.checkBoxRef[index].toggle();
      },

    }
  }
</script>

<style scoped>

</style>